package com.ruoyi.system.mapper;

import com.ruoyi.system.domain.ComingOut;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

@Mapper
public interface ComingOutMapper extends BaseMapper<ComingOut> {

    /**
     * 根据分类ID获取库存记录
     * @param categoryId 分类ID
     * @return 库存记录
     */
    @Select("SELECT * FROM tb_coming_out WHERE category_id = #{categoryId} AND del_flag = '0'")
    ComingOut selectByCategoryId(@Param("categoryId") Long categoryId);

    /**
     * 库存扣减/增加操作（乐观锁版本）
     * @param id 记录ID
     * @param comingIncrement 入库增量
     * @param outIncrement 出库增量
     * @param surplus 最新库存
     * @param version 版本号
     * @return 影响行数
     */
    @Update("UPDATE tb_coming_out SET " +
            "coming_count = coming_count + #{comingIncrement}, " +
            "out_count = out_count + #{outIncrement}, " +
            "surplus_count = #{surplus}, " +
            "version = version + 1, " +
            "update_time = NOW() " +
            "WHERE id = #{id} AND version = #{version}")
    int updateStockWithLock(@Param("id") Long id,
                            @Param("comingIncrement") Integer comingIncrement,
                            @Param("outIncrement") Integer outIncrement,
                            @Param("surplus") Integer surplus,
                            @Param("version") Integer version);



}